package slave

import (
	"backend/internal/common/errorx"
	"backend/internal/db/model"
	"context"
	"fmt"
	"gorm.io/gorm"
	"net/http"

	"backend/internal/svc"
	"backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSlaveIdListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetSlaveIdListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSlaveIdListLogic {
	return &GetSlaveIdListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetSlaveIdListLogic) GetSlaveIdList(req *types.SlaveIdList) (resp *types.SlaveIdListResponse, err error) {
	var device model.Device
	// 查询设备是否存在
	err = l.svcCtx.GormDB.Where("name = ?", req.DeviceName).First(&device).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			errorStr := fmt.Sprintf("Device %s not found", req.DeviceName)
			logx.Errorf(errorStr)
			return nil, errorx.NewDefaultError(errorStr)
		}
		errorStr := fmt.Sprintf("Failed to query device: %v", err)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	var slaves []model.Slave
	// 查询从站列表
	err = l.svcCtx.GormDB.Where("device_id = ?", device.ID).Find(&slaves).Error
	if err != nil {
		errorStr := fmt.Sprintf("查询从站失败: %v", err)
		logx.Errorf(errorStr)
		return nil, errorx.NewDefaultError(errorStr)
	}

	// 提取从站 ID
	slaveIds := make([]int32, len(slaves))
	for i, slave := range slaves {
		slaveIds[i] = slave.SlaveID
	}
	return &types.SlaveIdListResponse{
		Status: http.StatusOK,
		Data:   slaveIds,
		Msg:    "查询从站列表成功",
	}, nil
}
